package com.wuqing.consumer.interceptor;

import com.wuqing.DubboTransportFilter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * @author wuqing
 * @date 2020/8/8
 */
@WebFilter(urlPatterns = {"/hello", "/study"}, filterName = "IpGetFilter")
@Component
public class IpGetFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        System.out.println("进入过滤器，开始执行逻辑");
        String remoteAddr = servletRequest.getRemoteAddr();
        String serverName = servletRequest.getServerName();
        System.out.println("请求参数remoteAddr=" + remoteAddr + "，serverName=" + serverName);
        if (StringUtils.isNotBlank(remoteAddr)) {
            DubboTransportFilter.IpContext.setIp(remoteAddr);
        }
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            DubboTransportFilter.IpContext.release();
        }

    }

    @Override
    public void destroy() {

    }
}